package com.example.ktapplication.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.elvishew.xlog.XLog
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.R
import com.example.ktapplication.dialog.DialogLoading
import com.example.ktapplication.enum.MainClickEnum
import com.example.ktapplication.model.LoginViewModel
import com.example.ktapplication.model.RegisterViewModel
import com.example.ktapplication.state.LoginState
import com.example.ktapplication.state.RegisterState
import com.example.ktapplication.view.CustomTitleBar
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class RegisterActivity:AppCompatActivity() {

    private lateinit var titleBar: CustomTitleBar
    private lateinit var imgFind: ImageView
    private lateinit var imgMenu: ImageView
    private lateinit var txtTitle: TextView
    private lateinit var btnRegister: TextView
    private lateinit var registerTip: TextView
    private lateinit var userName: TextInputEditText
    private lateinit var pwd: TextInputEditText
    private lateinit var aPwd: TextInputEditText

    private lateinit var register: RegisterViewModel

    private var stateJob: Job? = null
    private var showDialog:Boolean = false
    private lateinit var mDialogLoading: DialogLoading

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        mDialogLoading =DialogLoading.instance
        register = ViewModelProvider(this)[RegisterViewModel::class.java]
        ///初始化组件
        initView()
    }

    fun initView(){
        titleBar=findViewById<CustomTitleBar>(R.id.titleBar)
        imgFind=titleBar.findViewById<ImageView>(R.id.img_find)
        imgFind.visibility= View.INVISIBLE
        imgMenu=titleBar.findViewById<ImageView>(R.id.img_menu)
        Glide.with(AppGlobals.getApplication()).load(R.mipmap.left).into(imgMenu)
        txtTitle=titleBar.findViewById<TextView>(R.id.txt_title)
        txtTitle.text="注册"

        btnRegister=findViewById<TextView>(R.id.btnLogin)
        registerTip=findViewById<TextView>(R.id.txtRegistTip)
        userName=findViewById<TextInputEditText>(R.id.etName)
        pwd=findViewById<TextInputEditText>(R.id.etPwd)
        aPwd=findViewById<TextInputEditText>(R.id.etaPwd)

        initEvent()
    }

    fun initEvent(){
        imgMenu.setOnClickListener(View.OnClickListener {
            finish()
        })
        registerTip.setOnClickListener(View.OnClickListener {
            val intent =  Intent(this, LoginActivity::class.java)
            startActivity(intent)
            finish()
        })
        btnRegister.setOnClickListener(View.OnClickListener {
            showDialog()
            var name="";
            name= userName.text.toString();
            var pwdS=""
            pwdS=pwd.text.toString();
            var pwdA=""
            pwdA=aPwd.text.toString();
            if (name.isEmpty()|| pwdS.isEmpty()||pwdA.isEmpty()){
                showToast("用户名或者密码不能为空")
            }else if (!pwdA.equals(pwdS)){
                showToast("两次密码不一致")
            }else{
                register.register(name,pwdS,pwdA)
            }
        })
        stateJob=lifecycleScope.launch(Dispatchers.IO) {
            ///IO线程
            register.state.collect{ state ->
                when(state){
                    is RegisterState.OnSuccess -> {
                        if (state.register!=null){
                            XLog.d(state.register!!.errorCode)
                            if(state.register!!.errorCode==0){
                                withContext(Dispatchers.Main){
                                    ///Main线程
                                    mDialogLoading.dismiss()
                                    intentLoginActivity()
                                }
                            }else{
                                showToast(state.register!!.errorMsg)
                            }
                            state.register!!.count+=1
                        }
                        dismissDialog()
                    }
                    is RegisterState.OnError -> {
                        dismissDialog()
                        val error = state.exception!!.message;
                        showToast(error.toString())
                    }
                }
            }
        }
    }

    private fun intentLoginActivity(){
        val intent =  Intent(this, LoginActivity::class.java)
        startActivity(intent)
        finish()
    }

    fun showDialog(){
        showDialog=true
        lifecycleScope.launch(Dispatchers.Main){

            mDialogLoading.setTip("账号注册中...")
            mDialogLoading.show(supportFragmentManager,"register")
        }
    }

    fun dismissDialog(){
        if (showDialog){
            lifecycleScope.launch(Dispatchers.Main){
                mDialogLoading.dismiss()
            }
        }
    }

    fun showToast(msg:String){
        lifecycleScope.launch(Dispatchers.Main){
            Toast.makeText(this@RegisterActivity,
                msg, Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        stateJob!!.cancel()
        super.onDestroy()
    }
}